#include "Button.h"

Button::Button(IArduino& arduino, MessageRouter& router, const String& name, ILogger& logger, int pin, int debounceDelay /* = 50*/)
: Service(arduino, router, name, logger), 
pin_(pin), 
prevValue_(arduino_.LOWVAL()), 
debounceDelay_(debounceDelay), 
lastDebounceTime_(0),
lastStableState_(arduino_.HIGHVAL()){
	arduino_.pin(pin_, arduino_.IN());
	arduino_.dWrite(pin_, arduino_.HIGHVAL());
}
void Button::tick(long milliseconds) {
	int value = arduino_.dRead(pin_);
	if(value != prevValue_){
		lastDebounceTime_ = milliseconds;
	}
	if(milliseconds - lastDebounceTime_ > debounceDelay_){
		if(value == arduino_.LOWVAL() && (lastStableState_ == arduino_.HIGHVAL()))
			postMessage(String(F("{\"event\":\"button\", \"id\":\"")) + getName() + F("\", \"state\":\"on\"}"));
		lastStableState_ = value;
	}
	prevValue_ = value;
}
